package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.annotation.Memcached;
import com.iddaa.core.annotation.MemcachedRead;
import com.iddaa.core.dao.LeagueDAO;
import com.iddaa.core.domain.League;
import com.iddaa.core.service.LeagueService;
import com.iddaa.core.service.SolrService;
import com.iddaa.core.util.Constants;

@Service("leagueService")
@Memcached(prefix = "League", expiration = Constants.Cache.LEAGUE_EXPIRETIME)
public class LeagueServiceImpl implements LeagueService {

	@Autowired
	private LeagueDAO leagueDAO;

	@Autowired
	private SolrService solrService;

	@Override
	public void saveLeague(League league) {
		leagueDAO.saveOrUpdate(league);
		solrService.updateSolr(league.getId(), league.getName(), "League");
		evictCache(league);
	}

	@Override
	@MemcachedRead
	public League findById(Long id) {
		return leagueDAO.getById(id);

	}

	@Override
	public Collection<League> loadLeagues() {
		return leagueDAO.loadAll();
	}

	@Override
	public void deleteLeague(Long id) {
		League league = findById(id);
		leagueDAO.delete(league);
		solrService.updateSolr(id,"League");
		deleteCache(id);

	}

	@Async
	public void evictCache(League league) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.set("League:" + league.getId(), Constants.Cache.LEAGUE_EXPIRETIME, league);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	public void deleteCache(Long id) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.delete("League:" + id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
